from app import app
from flask import Flask, render_template, request, jsonify, make_response
import random
from app.libs.QINIU import utoken,utoken_policy,delect as QiniuDel
import time
import hashlib
from app.admin.admin_login import *
from app.setting import API_SET
from app.models import *
import requests
def img_name():
    seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
    sa = []
    for i in range(16):
        sa.append(random.choice(seed))
    salt = ''.join(sa)
    return str(int(time.time()))+ salt

# 上传utkoen
@app.route('/pdd/upload/utoken', methods=["post", "get"])
@admin_require
def upload_utoken(aid):
   key = request.args.get("key",type=str)
   timestamp = request.args.get("timestamp",type=int)
   sign = request.args.get("sign")

   if key is None:
      return jsonify(code=-1,msg="The key is undefined ")
   if timestamp is None:
      return jsonify(code=-1,msg="The timestamp is undefined ")
   if sign is None:
      return jsonify(code=-1, msg="The sign is undefined ")

   if timestamp + 36000  < int(time.time()):
      return jsonify(code=-1, msg="The sign is invalidated ")

   m = hashlib.md5()
   data = key + "&" + str(timestamp) + "&" + API_SET.get("UPLOAD").get("access_key")
   data = data.encode(encoding='utf-8')
   m.update(data)
   sign1 = m.hexdigest()
   if sign1 != sign:
      return jsonify(code=-1, msg="The sign is invalidated ")

   key = img_name()
   ret = utoken(key)
   return jsonify(code=0,msg="获取成功",data=ret)

#上传策略 utoken
@app.route('/pdd/upload/utoken/policy', methods=["post", "get"])
@admin_require
def upload_utoken_policy(aid):
   key = request.args.get("key",type=str)
   fops = request.args.get("fops",type=str)
   timestamp = request.args.get("timestamp",type=int)
   sign = request.args.get("sign")

   if key is None:
      return jsonify(code=-1,msg="The key is undefined ")
   if timestamp is None:
      return jsonify(code=-1,msg="The timestamp is undefined ")
   if sign is None:
      return jsonify(code=-1, msg="The sign is undefined ")

   if timestamp + 36000  < int(time.time()):
      return jsonify(code=-1, msg="The sign is invalidated ")

   m = hashlib.md5()
   data = key + "&" + str(timestamp) + "&" + API_SET.get("UPLOAD").get("access_key")
   data = data.encode(encoding='utf-8')
   m.update(data)
   sign1 = m.hexdigest()
   if sign1 != sign:
      return jsonify(code=-1, msg="The sign is invalidated ")

   key = img_name()
   policy = {
       'persistentOps': fops,
   }
   print(policy)
   ret = utoken_policy(key=key,policy=policy)
   return jsonify(code=0,msg="获取成功",data=ret)

# #七牛云转码回调
# @app.route('/pdd/qiniu/delect', methods=["post", "get"])
# def qiniu_delect():
#     key = request.form.get("key",str)
#     if key is None:
#         return jsonify(code=-1,msg="The key is missing")
#
#     ret = QiniuDel(key)
#     if ret:
#         return jsonify(code=0,msg="succeed")
#     else:
#         return jsonify(code=-1, msg="Delete failed")


#服务器时间戳
@app.route('/pdd/timestamp', methods=["post", "get"])
def timestamp():
    return jsonify(code=0,msg="获取成功",timestamp=int(time.time()))

#七牛云pofp 状态查询
@app.route('/pdd/get/prefop', methods=["post", "get"])
def prefop():
    id = request.args.get("id",type=str)
    api_url = f'http://api.qiniu.com/status/get/prefop?id={id}'
    headers = {
        'Host': 'api.qiniu.com',

    }
    res = requests.post(api_url, headers=headers, timeout=30)
    print(res.content)
    print(res.status_code)
    print(res.headers)
    return res.json()


#七牛云转码回调
@app.route('/pdd/qiniu/callback/m3u8', methods=["post", "get"])
def upload_callback_m3u8():
    data = request.json

    persistentId = data.get("id")
    if not persistentId:
        return {
           "error":'presistentId is null'
        }
    vobj = Video.query.filter(Video.persistentId == persistentId).first()
    if not vobj:
        return {
            "error": 'presistentId is null'
        }

    if data.get("code")==0:

        vobj.live = data.get("items")[0].get("key")
        vobj.flag = 1

    elif data.get("code")==3:
        vobj.flag = 4

    try:
        db.session.commit()
    except:
        db.session.rollback()

    return "succeed"

